package com.zzyl.intercept;

import com.zzyl.properties.JwtConfigProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description JwtInterceptor
 * @Author liruzhuang
 * @Date 2024-10-17
 */
@Component
public class AdminJwtInterceptor implements HandlerInterceptor{
    @Autowired
    private JwtConfigProperties jwtConfigProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)){
            //不是就直接放行
            return true;
        }
        //获取请求头中的token
        String token = request.getHeader(jwtConfigProperties.getTokenName());
        try {
            //解析token
            Claims claims = JwtUtil.parseJWT(jwtConfigProperties.getBase64EncodedSecretKey(), token);
            Long userId = Long.valueOf(claims.get("userId").toString());
            UserThreadLocal.set(userId);
            return true;
        } catch (NumberFormatException e) {
            e.printStackTrace();
            response.setStatus(401);
            return false;
        }
    }
}
